<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex-0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数(动态)"></el-step>
        <el-step title="商品属性(静态)"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form :model="addFrom" ref="addFormRef" :rules="addFromRules">
        <!-- Tab标签页 -->
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave="beforeLeave" @tab-click="handleTabClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addFrom.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addFrom.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addFrom.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addFrom.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader v-model="addFrom.goods_cat" :options="cateList"
                :props="{ expandTrigger: 'hover', label:'cat_name',value:'cat_id'}" @change="handleChange" clearable>
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数(动态)" name="1">
            <el-form-item v-for="item in manyTableData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="item1" border v-for="(item1,index1) in item.attr_vals1" :key="index1">
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性(静态)" name="2">
            <el-form-item v-for="item in onlyTableData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload :headers="headersObj" action="http://42.192.71.221:8889/api/private/v1/upload"
              :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" list-type="picture"
              :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addFrom.goods_introduce">
            </quill-editor>
            <el-button style="margin:20px 0" type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

    </el-card>
    <el-dialog :visible.sync="previewImgDialog" width="50%">
      <img style="width:100%" :src="imgSrc" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      imgSrc: '',
      previewImgDialog: false,
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      fileList: [],
      manyTableData: [],
      onlyTableData: [],
      cateList: [],
      activeIndex: '0',
      addFrom: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [1, 3, 6],
        pics: [],
        goods_introduce: ''
      },
      addFromRules: {
        goods_name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    addGoods () {
      // 表单预验证
      this.$refs.addFormRef.validate(async (val) => {
        if (!val) return this.$message.error('亲，请填写必填项哟！！')
        console.log('验证通过')

        const form = JSON.parse(JSON.stringify(this.addFrom))
        form.goods_cat = form.goods_cat.join(',')
        // console.log(form, this.addFrom)
        // console.log(form === this.addFrom)
        form.attrs = []
        this.manyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          })
        })
        this.onlyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        // console.log(form)
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('创建失败')
        this.$message.success('创建成功')
        this.$router.go(-1)
      })
    },
    handleSuccess (response) {
      this.addFrom.pics.push({
        pic: response.data.tmp_path
      })
      console.log(this.addFrom.pics)
    },
    handlePreview ({ response: { data } }) {
      // console.log(response)
      this.imgSrc = 'http://42.192.71.221:8889/' + data.tmp_path
      this.previewImgDialog = true
    },
    handleRemove (file) {
      // console.log(file)
      const i = this.addFrom.pics.findIndex(item => {
        return item.pic === file.response.data.tmp_path
      })
      this.addFrom.pics.splice(i, 1)
    },
    async handleTabClick () {
      if (this.activeIndex === '1') {
        // 切换到动态参数
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        res.data.forEach(item => {
          item.attr_vals1 = item.attr_vals = item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
        // console.log(this.manyTableData)
      } else if (this.activeIndex === '2') {
        // 切换到动态参数
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        this.onlyTableData = res.data
        // console.log(this.onlyTableData)
      }
    },
    beforeLeave (to, from) {
      if (from === '0' && this.addFrom.goods_cat.length !== 3) {
        this.$message.error('请选择三级分类')
        return false
      }
    },
    handleChange () {
      // console.log(this.addFrom.goods_cat)
      if (this.addFrom.goods_cat.length !== 3) {
        this.addFrom.goods_cat = []
        return
      }
      console.log('可以操作')
    },
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类列表失败')
      this.cateList = res.data
      // console.log(this.cateList)
    }
  },
  computed: {
    cateId () {
      if (this.addFrom.goods_cat.length === 3) {
        return this.addFrom.goods_cat[2]
      }
      return null
    }
  },
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getCateList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
/deep/.ql-editor {
  min-height: 300px;
}
</style>
